<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class BasicCooperaterStatisticsTask extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('basic-cooperater-statistics-task')// 配置一个参数
            ->addArgument('date_str', Argument::OPTIONAL, '当天时间')
            ->setDescription('查询以前充值的数据(不包含当天)');
    }

    protected function execute(Input $input, Output $output)
    {
        $dateStr = $input->getArgument('date_str');
        if ($dateStr){
            $dateTime = date('Ymd', strtotime($dateStr));
            $month = date('Ym', strtotime($dateStr));
        }else{
            $dateTime = date('Ymd', time() - 86400);
            $month = date('Ym', time() - 86400);
        }

        // $doneTaskCount = DistributorsSharingStatistics::where('date',$dateTime)->count();
        // //任务已经跑过
        // if ($doneTaskCount > 0){
        //     return 0;
        // }

        //查询以前所有的数据
        //查询所有的剧id
        $whereId['is_delete']=0;
        $whereId['is_copy']=0;
        $videoIdData = Db::name('videos')->where($whereId)->field('id')->select()->toArray();
        $videoIds = array_column($videoIdData, 'id');
        //查询最早的充值时间
        $wherePay=[
            ['a.status', '=', 1],
            ['a.video_id', 'in', $videoIds]
        ];
        $videoEarliestData = Db::name('pay_record')->alias('a')->leftjoin('videos t1', 't1.id = a.video_id')->where($wherePay)->field('MIN(a.pay_time) AS earliest_recharge_time,a.video_id,t1.name as video_name,is_filings')->group('a.video_id')->select()->toArray();
        // var_dump($videoEarliestData);exit;
        //统计数据
        foreach($videoEarliestData as $k_E=>$v_E){
            $currentDate = date('Ymd', time() - 86400);
            // 获取需要统计的起始日期
            $startDate = date("Ymd", $videoEarliestData[$k_E]['earliest_recharge_time']); // 统计过去的数据，你可以根据需要进行调整

            // 遍历每一天进行统计
            while ($startDate <= $currentDate) {
                // 统计逻辑，根据需要进行具体的数据统计操作
                // 这里只是一个示例，你需要根据实际需求进行相应的统计代码编写
                $saveData = [];
                $dateTime = $startDate;
                // echo $startDate;exit;
                $month = date('Ym', $videoEarliestData[$k_E]['earliest_recharge_time']);

                $date = $startDate;
                $startTime = strtotime($date);
                $endTime = strtotime($date . ' 23:59:59');
                $videoIds=[];
                $videoIds[]=$videoEarliestData[$k_E]['video_id'];
                if($videoEarliestData[$k_E]['is_filings']>0){//存在复制剧
                    $videoIds[]=$videoEarliestData[$k_E]['is_filings'];
                }
                $where = [
                    ['status', '=', 1],
                    ['pay_time', '>=', $startTime],
                    ['pay_time', '<=', $endTime],
                    ['video_id', 'in', $videoIds]
                ];
                $payData = Db::name('pay_record')->where($where)->field('sum(total_fee) as total_amount')->select()->toArray();
                $rechargeDataAmount=!empty($payData) ? $payData[0]['total_amount'] : 0;
                // var_dump($rechargeDataAmount);exit;
                

                //自投充值
                $where_per=[
                    ['company_id', 'in', config('enum.self_company_id')]
                ];
                $distributor = Db::name('responsibility_person')->where($where_per)->field('id, name, commission_scale, scale, company_id')->select()->toArray();
                $pitcherIds = array_column($distributor, 'id');

                $linkData = Db::name('link')->where(['responsibility_person_id' => $pitcherIds])->field('id, responsibility_person_id')->select()->toArray();

                $linkIds = array_column($linkData, 'id');

                $whereSelf=[
                    ['status', '=', 1],
                    ['pay_time', '>=', $startTime],
                    ['pay_time', '<=', $endTime],
                    ['link_id', 'in', $linkIds],
                    ['video_id', 'in', $videoIds]

                ];
                $selfPayData = Db::name('pay_record')->where($whereSelf)->field('sum(total_fee) as total_amount')->select()->toArray();
                $selfDataAmount=!empty($selfPayData) ? $selfPayData[0]['total_amount'] : 0;
                // var_dump($selfDataAmount);exit;
                //写入数据
                $saveData[] = [
                    'date' => $dateTime,
                    'month' => $month,
                    'video_name' => $videoEarliestData[$k_E]['video_name'],
                    'video_id' => $videoEarliestData[$k_E]['video_id'],
                    'total_price' => round($rechargeDataAmount, 2),
                    'self_price' => round($selfDataAmount, 2),
                    'created_at' => time(),
                ];
                $bool = Db::name('daily_cooperater_statistics')->insertAll($saveData);
                // 递增日期
                $startDate = date("Ymd", strtotime($startDate . " +1 day"));
            }
        // var_dump($videoEarliestData[$k_E]);exit;
        }
        return $bool;
    }
}
